<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface Props {
  visible: boolean;
  pet?: any;
  currentRecords?: any[];
}

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'createNew', pet: any): void;
  (e: 'selectRecord', record: any): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const activeTab = ref('new');
const searchQuery = ref('');
const selectedRecord = ref<any>(null);
const previewVisible = ref(false);
const previewRecord = ref<any>(null);

// 模拟历史病历数据
const historicalRecords = ref([
  {
    id: 'HR001',
    recordNumber: 'NO202312010001',
    recordDate: dayjs('2023-12-01'),
    doctor: '孙医生',
    chiefComplaint: '食欲不振，精神萎靡，连续3天不进食',
    diagnosis: '急性肠胃炎',
    status: '已完成',
    createTime: '2023-12-01 09:30:00',
    temperature: 39.2,
    weight: 4.5,
    respiration: 20,
    heartRate: 120,
    examination: {
      earsEyesMouthNose: '眼结膜充血，鼻镜干燥',
      bonesMuscles: '正常',
      skinCoat: '毛发无光泽',
      lymphNodes: '下颌淋巴结轻度肿大',
      heartLungs: '心率稍快，肺部听诊正常',
      abdominalPalpation: '腹部紧张，有压痛',
    },
    labTests: [
      { name: '血常规', price: 80 },
      { name: '生化检查', price: 120 },
    ],
    prescriptions: [
      {
        group: 'A',
        name: '阿莫西林',
        specification: '0.25g*12片',
        unit: '片',
        usage: '口服',
        dosage: '1片',
        unitPrice: 15,
        quantity: 12,
        addedBy: '孙医生',
        remarks: '每日2次',
      },
      {
        group: 'B',
        name: '蒙脱石散',
        specification: '3g*6袋',
        unit: '袋',
        usage: '口服',
        dosage: '1袋',
        unitPrice: 8,
        quantity: 6,
        addedBy: '孙医生',
        remarks: '每日3次',
      },
    ],
    surgeries: [],
    treatments: [
      {
        name: '静脉输液',
        nurse: '王护士',
        room: '输液室1',
        treatmentDate: dayjs('2023-12-01'),
        price: 50,
      },
    ],
    doctorAdvice: '注意饮食卫生，避免生冷食物，按时服药，3天后复诊',
    precautions: '保持环境清洁，避免与其他宠物接触',
    followUpDate: dayjs('2023-12-04'),
  },
  {
    id: 'HR002',
    recordNumber: 'NO202311150002',
    recordDate: dayjs('2023-11-15'),
    doctor: '李医生',
    chiefComplaint: '皮肤瘙痒，脱毛，频繁抓挠',
    diagnosis: '过敏性皮肤病',
    status: '已完成',
    createTime: '2023-11-15 14:20:00',
    temperature: 38.5,
    weight: 4.2,
    respiration: 18,
    heartRate: 110,
    examination: {
      earsEyesMouthNose: '正常',
      bonesMuscles: '正常',
      skinCoat: '多处脱毛，皮肤发红',
      lymphNodes: '正常',
      heartLungs: '正常',
      abdominalPalpation: '正常',
    },
    labTests: [
      { name: '皮肤刮片检查', price: 60 },
      { name: '过敏原检测', price: 200 },
    ],
    prescriptions: [
      {
        group: 'A',
        name: '泼尼松',
        specification: '5mg*20片',
        unit: '片',
        usage: '口服',
        dosage: '1片',
        unitPrice: 12,
        quantity: 20,
        addedBy: '李医生',
        remarks: '每日1次',
      },
    ],
    surgeries: [],
    treatments: [
      {
        name: '药浴治疗',
        nurse: '张护士',
        room: '治疗室2',
        treatmentDate: dayjs('2023-11-15'),
        price: 80,
      },
    ],
    doctorAdvice: '避免接触过敏原，保持皮肤清洁，按时服药',
    precautions: '避免使用刺激性洗护用品',
    followUpDate: dayjs('2023-11-22'),
  },
  {
    id: 'HR003',
    recordNumber: 'NO202310200003',
    recordDate: dayjs('2023-10-20'),
    doctor: '张医生',
    chiefComplaint: '咳嗽，流鼻涕，打喷嚏',
    diagnosis: '上呼吸道感染',
    status: '已完成',
    createTime: '2023-10-20 11:15:00',
    temperature: 39.8,
    weight: 4,
    respiration: 25,
    heartRate: 130,
    examination: {
      earsEyesMouthNose: '鼻分泌物增多，咽喉充血',
      bonesMuscles: '正常',
      skinCoat: '正常',
      lymphNodes: '颈部淋巴结轻度肿大',
      heartLungs: '肺部有湿啰音',
      abdominalPalpation: '正常',
    },
    labTests: [
      { name: '血常规', price: 80 },
      { name: 'X光检查', price: 150 },
    ],
    prescriptions: [
      {
        group: 'A',
        name: '头孢克肟',
        specification: '0.1g*10片',
        unit: '片',
        usage: '口服',
        dosage: '1片',
        unitPrice: 18,
        quantity: 10,
        addedBy: '张医生',
        remarks: '每日2次',
      },
      {
        group: 'B',
        name: '止咳糖浆',
        specification: '100ml',
        unit: '瓶',
        usage: '口服',
        dosage: '5ml',
        unitPrice: 25,
        quantity: 1,
        addedBy: '张医生',
        remarks: '每日3次',
      },
    ],
    surgeries: [],
    treatments: [
      {
        name: '雾化治疗',
        nurse: '李护士',
        room: '雾化室',
        treatmentDate: dayjs('2023-10-20'),
        price: 60,
      },
    ],
    doctorAdvice: '多休息，保持室内通风，按时服药',
    precautions: '避免受凉，注意保暖',
    followUpDate: dayjs('2023-10-27'),
  },
]);

// 计算属性
const filteredRecords = computed(() => {
  if (!searchQuery.value) return historicalRecords.value;

  return historicalRecords.value.filter(
    (record) =>
      record.recordNumber
        .toLowerCase()
        .includes(searchQuery.value.toLowerCase()) ||
      record.chiefComplaint
        .toLowerCase()
        .includes(searchQuery.value.toLowerCase()) ||
      record.diagnosis
        .toLowerCase()
        .includes(searchQuery.value.toLowerCase()) ||
      record.doctor.toLowerCase().includes(searchQuery.value.toLowerCase()),
  );
});

// 方法
const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  activeTab.value = 'new';
  searchQuery.value = '';
  selectedRecord.value = null;
};

const handleCreateNew = () => {
  if (!props.pet) {
    message.warning('请先选择宠物');
    return;
  }

  emit('createNew', props.pet);
  handleCancel();
  message.success('已创建新病历');
};

const handleSelectRecord = (record: any) => {
  selectedRecord.value = record;
};

const handlePreviewRecord = (record: any) => {
  previewRecord.value = record;
  previewVisible.value = true;
};

const handleClosePreview = () => {
  previewVisible.value = false;
  previewRecord.value = null;
};

const handleConfirmSelect = () => {
  if (!selectedRecord.value) {
    message.warning('请选择要复制的病历');
    return;
  }

  emit('selectRecord', selectedRecord.value);
  handleCancel();
  message.success('已选择历史病历');
};

const getStatusColor = (status: string) => {
  switch (status) {
    case '已完成': {
      return 'success';
    }
    case '待处理': {
      return 'warning';
    }
    case '进行中': {
      return 'processing';
    }
    default: {
      return 'default';
    }
  }
};

// 监听visible变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="病例管理"
    width="800px"
    :footer="null"
    @cancel="handleCancel"
    @update:visible="(val) => emit('update:visible', val)"
  >
    <div class="case-management">
      <!-- 标签页 -->
      <a-tabs
        :active-key="activeTab"
        class="case-tabs"
        @update:active-key="(val) => (activeTab = val)"
      >
        <a-tab-pane key="new" tab="新建病历">
          <div class="new-case-section">
            <div class="section-header">
              <h4>📝 新建空白病历</h4>
              <p class="section-desc">
                为当前宠物创建一个全新的病历，开始新的诊疗记录
              </p>
            </div>

            <div class="pet-info" v-if="pet">
              <a-card size="small">
                <div class="pet-details">
                  <div class="pet-avatar">
                    <a-avatar :size="40">
                      {{ pet.type === '猫类' ? '🐱' : '🐕' }}
                    </a-avatar>
                  </div>
                  <div class="pet-info-text">
                    <div class="pet-name">{{ pet.name }}</div>
                    <div class="pet-owner">主人: {{ pet.ownerName }}</div>
                    <div class="pet-contact">电话: {{ pet.contact }}</div>
                  </div>
                </div>
              </a-card>
            </div>

            <div class="action-section">
              <a-button type="primary" size="large" @click="handleCreateNew">
                🆕 创建新病历
              </a-button>
              <p class="action-tip">点击创建新病历，将开始一个全新的诊疗记录</p>
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="history" tab="历史病历">
          <div class="history-section">
            <div class="section-header">
              <h4>📋 选择历史病历</h4>
              <p class="section-desc">
                选择历史病历进行复制，保留原有数据作为参考
              </p>
            </div>

            <!-- 搜索框 -->
            <div class="search-section">
              <a-input
                :value="searchQuery"
                placeholder="搜索病历编号、主诉、诊断或医生"
                allow-clear
                @update:value="(val) => (searchQuery = val)"
              >
                <template #prefix> 🔍 </template>
              </a-input>
            </div>

            <!-- 病历列表 -->
            <div class="records-list">
              <a-radio-group
                :value="selectedRecord"
                class="records-group"
                @update:value="(val) => (selectedRecord = val)"
              >
                <div
                  v-for="record in filteredRecords"
                  :key="record.id"
                  class="record-item"
                  :class="{ selected: selectedRecord?.id === record.id }"
                >
                  <a-radio :value="record" class="record-radio">
                    <div class="record-content">
                      <div class="record-header">
                        <div class="record-number">
                          {{ record.recordNumber }}
                        </div>
                        <a-tag :color="getStatusColor(record.status)">
                          {{ record.status }}
                        </a-tag>
                      </div>
                      <div class="record-info">
                        <div class="record-date">
                          📅 {{ record.recordDate.format('YYYY-MM-DD') }}
                        </div>
                        <div class="record-doctor">👨‍⚕️ {{ record.doctor }}</div>
                      </div>
                      <div class="record-details">
                        <div class="complaint">
                          <strong>主诉:</strong> {{ record.chiefComplaint }}
                        </div>
                        <div class="diagnosis">
                          <strong>诊断:</strong> {{ record.diagnosis }}
                        </div>
                      </div>
                      <div class="record-actions">
                        <a-button
                          type="link"
                          size="small"
                          @click.stop="handlePreviewRecord(record)"
                        >
                          👁️ 预览病历
                        </a-button>
                      </div>
                    </div>
                  </a-radio>
                </div>
              </a-radio-group>

              <!-- 空状态 -->
              <div v-if="filteredRecords.length === 0" class="empty-state">
                <div class="empty-icon">📄</div>
                <div class="empty-text">
                  {{ searchQuery ? '未找到匹配的病历' : '暂无历史病历' }}
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-section">
              <a-button
                type="primary"
                size="large"
                :disabled="!selectedRecord"
                @click="handleConfirmSelect"
              >
                📋 选择此病历
              </a-button>
              <p class="action-tip">选择后将复制该病历的数据作为新病历的基础</p>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 病历预览模态框 -->
    <a-modal
      :visible="previewVisible"
      title="病历预览"
      width="900px"
      :footer="null"
      @cancel="handleClosePreview"
      @update:visible="(val) => (previewVisible = val)"
    >
      <div v-if="previewRecord" class="record-preview">
        <!-- 基本信息 -->
        <div class="preview-section">
          <h4>📋 基本信息</h4>
          <a-descriptions :column="3" bordered size="small">
            <a-descriptions-item label="病历编号">
              {{ previewRecord.recordNumber }}
            </a-descriptions-item>
            <a-descriptions-item label="就诊日期">
              {{ previewRecord.recordDate.format('YYYY-MM-DD') }}
            </a-descriptions-item>
            <a-descriptions-item label="主治医生">
              {{ previewRecord.doctor }}
            </a-descriptions-item>
            <a-descriptions-item label="体温">
              {{ previewRecord.temperature }}°C
            </a-descriptions-item>
            <a-descriptions-item label="体重">
              {{ previewRecord.weight }}kg
            </a-descriptions-item>
            <a-descriptions-item label="心率">
              {{ previewRecord.heartRate }}次/分
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 主诉 -->
        <div class="preview-section">
          <h4>🏥 主诉</h4>
          <div class="preview-content">{{ previewRecord.chiefComplaint }}</div>
        </div>

        <!-- 体检检查 -->
        <div class="preview-section">
          <h4>🔍 体检检查</h4>
          <a-descriptions :column="2" bordered size="small">
            <a-descriptions-item label="眼耳口鼻">
              {{ previewRecord.examination.earsEyesMouthNose }}
            </a-descriptions-item>
            <a-descriptions-item label="骨骼肌肉">
              {{ previewRecord.examination.bonesMuscles }}
            </a-descriptions-item>
            <a-descriptions-item label="皮肤被毛">
              {{ previewRecord.examination.skinCoat }}
            </a-descriptions-item>
            <a-descriptions-item label="淋巴结">
              {{ previewRecord.examination.lymphNodes }}
            </a-descriptions-item>
            <a-descriptions-item label="心肺">
              {{ previewRecord.examination.heartLungs }}
            </a-descriptions-item>
            <a-descriptions-item label="腹部触诊">
              {{ previewRecord.examination.abdominalPalpation }}
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 检验项目 -->
        <div v-if="previewRecord.labTests?.length > 0" class="preview-section">
          <h4>🔬 检验项目</h4>
          <a-table
            :columns="[
              { title: '项目名称', dataIndex: 'name', key: 'name' },
              { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
            ]"
            :data-source="previewRecord.labTests"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 处方 -->
        <div
          v-if="previewRecord.prescriptions?.length > 0"
          class="preview-section"
        >
          <h4>💊 处方</h4>
          <a-table
            :columns="[
              { title: '编组', dataIndex: 'group', key: 'group', width: 60 },
              { title: '名称', dataIndex: 'name', key: 'name' },
              {
                title: '规格',
                dataIndex: 'specification',
                key: 'specification',
                width: 120,
              },
              { title: '用法', dataIndex: 'usage', key: 'usage', width: 80 },
              { title: '用量', dataIndex: 'dosage', key: 'dosage', width: 80 },
              {
                title: '数量',
                dataIndex: 'quantity',
                key: 'quantity',
                width: 60,
              },
              {
                title: '备注',
                dataIndex: 'remarks',
                key: 'remarks',
                width: 100,
              },
            ]"
            :data-source="previewRecord.prescriptions"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 处置项目 -->
        <div
          v-if="previewRecord.treatments?.length > 0"
          class="preview-section"
        >
          <h4>🩺 处置项目</h4>
          <a-table
            :columns="[
              { title: '处置名称', dataIndex: 'name', key: 'name' },
              { title: '护士', dataIndex: 'nurse', key: 'nurse', width: 100 },
              { title: '处置室', dataIndex: 'room', key: 'room', width: 100 },
              {
                title: '处置日期',
                dataIndex: 'treatmentDate',
                key: 'treatmentDate',
                width: 120,
              },
              { title: '价格', dataIndex: 'price', key: 'price', width: 80 },
            ]"
            :data-source="previewRecord.treatments"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 诊断 -->
        <div class="preview-section">
          <h4>🏥 诊断</h4>
          <div class="preview-content">{{ previewRecord.diagnosis }}</div>
        </div>

        <!-- 医嘱 -->
        <div class="preview-section">
          <h4>📝 医嘱</h4>
          <div class="preview-content">{{ previewRecord.doctorAdvice }}</div>
        </div>

        <!-- 注意事项 -->
        <div class="preview-section">
          <h4>⚠️ 注意事项</h4>
          <div class="preview-content">{{ previewRecord.precautions }}</div>
        </div>

        <!-- 复诊安排 -->
        <div class="preview-section">
          <h4>📅 复诊安排</h4>
          <div class="preview-content">
            {{
              previewRecord.followUpDate
                ? previewRecord.followUpDate.format('YYYY-MM-DD')
                : '未安排'
            }}
          </div>
        </div>
      </div>
    </a-modal>
  </a-modal>
</template>

<style scoped>
.case-management {
  padding: 16px 0;
}

.case-tabs {
  min-height: 400px;
}

.section-header {
  margin-bottom: 24px;
  text-align: center;
}

.section-header h4 {
  margin: 0 0 8px;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.section-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.new-case-section,
.history-section {
  padding: 20px 0;
}

.pet-info {
  margin-bottom: 24px;
}

.pet-details {
  display: flex;
  gap: 12px;
  align-items: center;
}

.pet-info-text {
  flex: 1;
}

.pet-name {
  margin-bottom: 4px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.pet-owner,
.pet-contact {
  margin-bottom: 2px;
  font-size: 14px;
  color: #666;
}

.search-section {
  margin-bottom: 20px;
}

.records-list {
  max-height: 300px;
  padding: 12px;
  margin-bottom: 20px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.records-group {
  width: 100%;
}

.record-item {
  margin-bottom: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  transition: all 0.3s;
}

.record-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 10%);
}

.record-item.selected {
  background: #f6ffed;
  border-color: #1890ff;
}

.record-radio {
  width: 100%;
  padding: 12px;
}

.record-radio :deep(.ant-radio) {
  display: none;
}

.record-content {
  width: 100%;
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.record-number {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.record-info {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.record-details {
  font-size: 13px;
  line-height: 1.5;
}

.complaint,
.diagnosis {
  margin-bottom: 4px;
}

.empty-state {
  padding: 40px 20px;
  color: #999;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-text {
  font-size: 16px;
}

.action-section {
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.action-tip {
  margin: 12px 0 0;
  font-size: 12px;
  color: #666;
}

:deep(.ant-tabs-content-holder) {
  padding: 0;
}

:deep(.ant-tabs-tabpane) {
  padding: 0;
}

/* 病历预览样式 */
.record-preview {
  max-height: 600px;
  overflow-y: auto;
}

.preview-section {
  margin-bottom: 24px;
}

.preview-section h4 {
  padding-bottom: 4px;
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  border-bottom: 2px solid #1890ff;
}

.preview-content {
  padding: 12px;
  line-height: 1.6;
  color: #262626;
  background: #fafafa;
  border-radius: 4px;
}

.record-actions {
  margin-top: 8px;
  text-align: right;
}

.record-actions .ant-btn {
  height: auto;
  padding: 0;
  font-size: 12px;
}
</style>
